package es.unex.meigas.gvsig.gui;

import java.awt.event.WindowEvent;
import java.util.ArrayList;

import javax.swing.JOptionPane;

import com.iver.andami.PluginServices;
import com.iver.andami.ui.mdiManager.IWindowListener;
import com.iver.andami.ui.mdiManager.SingletonWindow;
import com.iver.andami.ui.mdiManager.WindowInfo;
import com.iver.cit.gvsig.ProjectExtension;
import com.iver.cit.gvsig.fmap.MapContext;
import com.iver.cit.gvsig.project.Project;
import com.iver.cit.gvsig.project.documents.view.ProjectView;
import com.iver.cit.gvsig.project.documents.view.ProjectViewFactory;

import es.unex.meigas.core.Meigas;
import es.unex.meigas.extLoadSaveProject.SaveProjectExtension;
import es.unex.meigas.gui.MeigasPanel;

public class gvMeigasWindow extends MeigasPanel implements SingletonWindow, IWindowListener {

	private LayersListener m_LayersListener;
	private WindowInfo viewInfo;

	protected gvMeigasWindow() {

		super();
		addListeners();

	}

	public void windowClosed() {

		removeListeners();
		Meigas.getInputFactory().clearDataObjects();
		//Meigas.setMainFrame(null);

	}

	private void addListeners() {

		m_LayersListener = new LayersListener();
		Project project = ((ProjectExtension)PluginServices.getExtension(ProjectExtension.class)).getProject();
		ArrayList views = project.getDocumentsByType(ProjectViewFactory.registerName);
		for (int i = 0; i < views.size(); i++) {
			ProjectView view = (ProjectView) views.get(i);
			MapContext mapContext = view.getMapContext();
			mapContext.getLayers().addLayerCollectionListener(m_LayersListener);
		}

	}

	private void removeListeners() {

		Project project = ((ProjectExtension)PluginServices.getExtension(ProjectExtension.class)).getProject();
		ArrayList views = project.getDocumentsByType(ProjectViewFactory.registerName);
		for (int i = 0; i < views.size(); i++) {
			ProjectView view = (ProjectView) views.get(i);
			MapContext mapContext = view.getMapContext();
			mapContext.getLayers().removeLayerCollectionListener(m_LayersListener);
		}

	}

	public WindowInfo getWindowInfo() {

        if (viewInfo == null) {
            viewInfo=new WindowInfo(WindowInfo.MODELESSDIALOG | WindowInfo.RESIZABLE);
        }
        return viewInfo;

	}

	public Object getWindowModel() {

		return "Meigas";

	}

	public void windowActivated() {}

}
